<?php
/**
 * Created by PhpStorm.
 * User: xunuo
 * Date: 2017/6/26
 * Time: 11:17
 */
/**
 * 检查节点权限
 * @param $nodeName
 * @param int $roleId
 * @return bool
 */
function check($nodeName, $roleId = 0)
{
    if (empty($roleId)) {
        $roleId = session('admin.role_id');
    }
    //节点状态检查
    $node = db('node')
        ->where('node_name', $nodeName)
        ->where('is_delete', 0)
        ->find();
    if (!$node) {
        return false;
    }
    //角色状态检查
    $role = db('role')
        ->where('id', $roleId)
        ->where('is_delete', 0)
        ->find();
    if (!$role) {
        return false;
    }
    //权限检查
    $access = db('access')
        ->where('node_id', $node['id'])
        ->where('role_id', $role['id'])
        ->find();
    if ($access) {
        return true;
    } else {
        //检查子节点
        $nodeList = db('node')
            ->where('pid', $node['id'])
            ->where('is_delete', 0)
            ->select();
        foreach ($nodeList as $node) {
            if (check($node['node_name'], $role['id'])) {
                return true;
            }
        }
        return false;
    }
}

/**
 * 获取小程序access_token
 */
function get_mp_access_token($id)
{
    //第三方信息获取
    $component = db('component')->where('id',1)->find();
    $row = db('mp')->where('id',$id)->find();
    //判断access_token是否有效
    if ($row['access_token_create_time'] + $row['access_token_expire'] >= time()) {
        return $row['access_token'];
    }
    //刷新access_token
    $param = [
        'component_appid' => $component['appid'],
        'authorizer_appid' => $row['appid'],
        'authorizer_refresh_token' => $row['refresh_token'],
    ];
    $result = https_request('https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token='
        . $component['access_token'], json_encode($param));
    $result = json_decode($result, true);
    $data['access_token'] = $result['authorizer_access_token'];
    $data['access_token_expire'] = $result['expires_in'];
    $data['access_token_create_time'] = time();
    $refresh_token = $result['authorizer_refresh_token'];
    if (empty($data['access_token']) || empty($data['access_token_expire']) || empty($refresh_token)) {
        throw new Exception('获取access_token失败');
    }
    $mpInfo = db('mp')->where('id',$id)->update($data);
    if (!$mpInfo)
    {
        throw new Exception('修改mp表信息失败');
    }
    return $data['access_token'];
}

//https请求（支持GET和POST）
function https_request($url, $data = null)
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    if (!empty($data)) {
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($curl);
    curl_close($curl);
    return $output;
}

/**
 * 检测手机号码格式
 * @param  [type] $mobile
 * @return [type]
 */
function checkMobile($mobile)
{
    if (preg_match("/^1[35789]{1}[0-9]{9}$|14[57]{1}[0-9]{8}$/", $mobile)) {
        return true;
    } else {
        return false;
    }
}

//获取省市区
function region_name($id)
{
    return db('region')->where('id', $id)->value('name');
}

/**
 * 检测手机号码格式
 * @param  [type] $mobile
 * @return [type]
 */
function checkTelephone($mobile)
{
    if (preg_match("/^([0-9]{3,4}-)?[0-9]{7,8}$/", $mobile)) {
        return true;
    } else {
        return false;
    }
}

/**
 * 根据角色ID获取角色名
 * @param $roleId
 * @return mixed
 */
function get_role_name($roleId)
{
    return db('role')->where('id', $roleId)->find()['role_name'];
}

/**
 * 判断帐号是否已存在
 * @param $userAccount
 * @return bool
 */
function account_exist($userAccount)
{
    $user = db('admin_user')->where('user_account', $userAccount)->find();
    if ($user) {
        return true;
    } else {
        return false;
    }
}

/**
 * 根据节点ID检查权限
 * @param $nodeId
 * @param $roleId
 * @return bool
 */
function check_id($nodeId, $roleId)
{
    $access = db('access')
        ->where('node_id', $nodeId)
        ->where('role_id', $roleId)
        ->find();
    if ($access) {
        return true;
    } else {
        return false;
    }
}

/**
 * 通过id查询信息
 */
function get_info($table_name,$map,$value) {

    if(empty($value)) {
        $result = db($table_name)
            ->where($map)
            ->find();
    } else {
        $result = db($table_name)
            ->field($value)
            ->where($map)
            ->find();
    }

    return $result;

}

/**
 * 通过id返回某个字段
 */
function get_value($id,$table_name,$field,$value,$is_delete) {
    $map[$field] = $id;

    if(!empty($is_delete)) {
        $result = db($table_name)
            ->where($map)
            ->value($value);
    } else {
        $result = db($table_name)
            ->where('is_delete',0)
            ->where($map)
            ->value($value);
    }

    return $result;
}

/**
 * 车辆类型
 */
function get_license_type($id) {
    $result = db('vehicle')
        ->where('id', $id)
        ->value('title');
    //switch ($id) {
    //    case 1:
    //    $result = '小型车';
    //    break;
    //
    //    case 2:
    //    $result = '中型车';
    //    break;
    //
    //    case 3:
    //    $result = '大型车';
    //    break;
    //
    //    case 4:
    //    $result = '挂车';
    //    break;
    //
    //    default:
    //    $result = '暂无信息';
    //    break;
    //}
    return $result;
}

/**
 * 通过某个条件筛选相应数据
 */
function get_list($table_name,$data,$value,$pageNum, $numPerPage,$count) {

    if(empty($count)) {
        $list = db($table_name)
            ->field($value)
            ->where($data)
            ->page($pageNum, $numPerPage)
            ->select();
    } else {
        $list = db($table_name)
            ->where($data)
            ->count();
    }

    return $list;
}
//通过订单id获取订单编号
function get_order_sn($id)
{
    return db('order')->where('order_id', $id)->value('order_sn');
}
//获取商家名称
function get_company_name($id)
{
    return db('company')->where('id', $id)->value('company_name');
}
/**
 * 是否已结算
 */
function get_is_distribut($id) {
    switch ($id) {
        case 0:
            $result = '未结算';
            break;

        case 1:
            $result = '已结算';
            break;

        case 2:
            $result = '无效订单';
            break;

        default:
            $result = '暂无信息';
            break;
    }

    return $result;
}
/**
 * @Desc 随机字符串
 *
 * @param int $length 个数
 *
 * @return string
 */
function randomChar($length = 8)
{
    $char = '';
    $str = 'abcdefghjklmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';
    $max = strlen($str) - 1;
    for ($i = 0; $i < $length; $i++) {
        $char .= $str{random_int(0, $max)};
    }
    return $char;
}